import {
  Form,
  Input,
  message,
  ModalProps,
  // Slider,
  Switch,
  Tooltip,
} from 'antd';
import { debounce } from 'lodash';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';

import modelService from '@/api/services/modelService';
import { GetModelListModels, GetModelListReq, GetModelListRes } from '@/common/types';
import Slider from '@/components/Antd/Slider';
import GradientBox from '@/components/GradientBox';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import ModalsBoxContent from '@/components/modals/ModalsBoxContent';
import ModalsFooterBtn from '@/components/modals/ModalsFooterBtn';
import NotData from '@/components/NotData';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { SettingAIDataType } from '@/types/app/type';

const modelTitle = {
  llm: '语言模型',
  funcCall: '工具调用模型',
  rerank: '重排模型',
  embedding: '索引模型',
  non: '非默认模型',
  tt: '语音模型',
  stt: '语音转文本模型',
  tts: '文本转语音模型',
};

interface Props extends ModalProps {
  api?: (list: GetModelListReq) => Promise<GetModelListRes>;
  defaultValue: SettingAIDataType;
  onSubmit: (value: SettingAIDataType) => void;
  isWorkflow?: boolean;
  onSelectValue?: (selectModel: GetModelListModels | undefined) => void;
}

function DialogModelSelect({
  defaultValue,
  onSubmit,
  api,
  isWorkflow = true,
  onSelectValue,
  ...props
}: Props) {
  const [modelList, setModelList] = useState<GetModelListModels[]>([]);
  const [selectValue, setSelectValue] = useState<GetModelListModels>();
  const [listPagination, setListPagination] = useState<GetModelListReq>({
    offset: -1,
    page: 1,
    pageSize: 9999999,
    searchText: '',
    modelType: ['llm'],
    isActive: true,
  });
  const [listSearchText, setListSearchText] = useState<string>('');
  const [scrollIntoValue, setScroolIntoValue] = useState<number>(0);

  const { appDetail, configurations } = useOrchestrationStore();

  const useReasoning = useMemo(() => selectValue?.metadata.reasoning !== undefined, [selectValue]);
  const useConfigurations = useMemo(
    () => configurations.find((item) => item.name === 'deep_think'),
    [configurations],
  );

  const listRef = useRef<HTMLDivElement>(null);

  const [form] = Form.useForm();

  const [messageApi, contextHolder] = message.useMessage();

  useEffect(() => {
    if (defaultValue) {
      form.setFieldsValue(defaultValue);
    }
  }, [defaultValue]);

  useEffect(() => {
    getModelList();
  }, [listPagination, defaultValue, useConfigurations]);

  useEffect(() => {
    if (props.open && listRef.current) {
      setTimeout(() => {
        const listElement = listRef.current;

        listElement?.scrollTo({
          top: scrollIntoValue, // 目标位置
          behavior: 'smooth', // 平滑滚动
        });
      }, 0);
    }
  }, [props.open, scrollIntoValue, listRef]);

  const getModelList = async () => {
    try {
      const result = await (api
        ? api({ ...listPagination, enableReasoning: useConfigurations !== undefined })
        : modelService.getModelList({
            ...listPagination,
            enableReasoning: useConfigurations !== undefined,
          }));
      const resultFind = result.list.find((item) => item.metadata.name === defaultValue?.model);
      const boxIndex = result.list.findIndex((item) => item.metadata.name === defaultValue?.model);

      if (resultFind?.metadata.reasoning !== undefined && resultFind) {
        form.setFieldsValue({
          ...defaultValue,
          enableReasoning:
            defaultValue.enableReasoning !== undefined
              ? defaultValue.enableReasoning
              : resultFind?.metadata.reasoning,
        });
      }

      // console.log('resultFind', resultFind);

      const boxHeight = boxIndex * 76;
      setScroolIntoValue(boxHeight);
      // setScroolIntoValue(boxIndex * 76);
      setSelectValue(resultFind);
      setModelList(result.list);
    } catch (e) {
      console.log(e);
    }
  };

  const handleSelectValue = (value: GetModelListModels) => {
    if (defaultValue && value.metadata.model === defaultValue?.model) {
      setSelectValue(value);
      form.setFieldsValue({ ...defaultValue, isResponseAnswerText: true });
    } else {
      setSelectValue(value);
      form.setFieldsValue({
        temperature: 0.3,
        maxToken: Math.floor(value.metadata.maxResponse / 3),
        enableReasoning: value.metadata.reasoning,
        isResponseAnswerText: true,
      });
    }
  };

  const handleSearchText = (value: string) => {
    setListSearchText(value);
    handleSearchTextFn(value);
  };

  const handleSearchTextFn = useCallback(
    debounce((text) => {
      setListPagination((prev) => {
        return {
          ...prev,
          searchText: text,
        };
      });
    }, 500),
    [listPagination],
  );

  const handleSubmit = (value: any) => {
    if (JSON.stringify(value) === '{}') {
      messageApi.open({
        type: 'error',
        content: '请选择模型',
      });
      return;
    }

    let result: SettingAIDataType = {
      model: selectValue?.metadata.model as string,
      ...value,
    };

    if (isWorkflow) {
      result = { ...result, isResponseAnswerText: value.isResponseAnswerText };
    }

    if (
      (isWorkflow || !selectValue?.metadata.onlyThinkMode) &&
      value.enableReasoning !== undefined
    ) {
      result = { ...result, enableReasoning: value.enableReasoning };
    }

    onSubmit(result);
  };

  useEffect(() => {
    onSelectValue && onSelectValue(selectValue);
  }, [selectValue]);

  function ModalsFooter() {
    return (
      <div
        className="flex  items-center justify-between px-4 py-3"
        style={{
          borderTop: '1px solid #E5E6EB',
        }}
      >
        {selectValue && !selectValue.metadata.isRecommend && appDetail.isCreateFromTemplate ? (
          <div className="flex items-center">
            <div className="mr-[2px] flex h-6 w-6 items-center justify-center">
              <SvgIcon icon="warning" size={16} color="#FF9226" />
            </div>
            <span className="text-sm leading-6 text-@warning-color">
              使用非推荐模型，无法确保其使用效果
            </span>
          </div>
        ) : (
          <div />
        )}
        <div className="flex items-center gap-3">
          <ModalsFooterBtn onClick={props.onCancel}>取消</ModalsFooterBtn>
          <ModalsFooterBtn
            type="primary"
            onClick={form.submit}
            disabled={selectValue === undefined}
          >
            确认
          </ModalsFooterBtn>
        </div>
      </div>
    );
  }

  return (
    <Modals
      {...props}
      title="AI模型"
      width={960}
      onOk={() => {
        form.submit();
      }}
      footer={<ModalsFooter />}
    >
      {contextHolder}
      <div className="flex">
        <div className="flex-1">
          <div className="pr-6">
            <Input
              placeholder="请输入内容"
              suffix={<SvgIcon icon="searchModel" size={16} color="text-text-4" />}
              className="mb-4 "
              value={listSearchText}
              onChange={(e) => handleSearchText(e.target.value)}
            />
          </div>

          {/* <div className="flex flex-wrap gap-2">
            {listData?.map((item) => (
              <div
                key={item.name}
                className={`flex cursor-pointer items-center gap-1 rounded-md px-[10px] py-[2px] ${
                  selectData?.name === item.name
                    ? 'bg-@brand-color-gradient text-white'
                    : 'bg-gradient-to-t from-fill-1 to-fill-1 text-text-4'
                }`}
                onClick={() => handleSelectData(item)}
              >
                {item.avatar.length > 0 && (
                  <SvgIcon
                    icon={item.avatar}
                    size={20}
                    className="rounded-full border-[1px] border-solid border-line-2"
                  />
                )}
                <span className="text-sm leading-[22px]">{item.name}</span>
              </div>
            ))}
          </div> */}

          {/* <div className="flex h-[408px] flex-col gap-2 overflow-y-auto" ref={listRef}>
            {modelList.map((item) => (
              <GradientBox
                key={item.id}
                onClick={() => (!item.isConnect ? undefined : handleSelectValue(item))}
                className={`h-[72px] ${
                  !item.isConnect ? '!cursor-not-allowed' : ''
                } flex items-center py-3 pl-4`}
                active={item.metadata.name === selectValue?.metadata.name}
                hover={item.isConnect}
              >
                <SvgIcon icon={item.metadata.avatar} size={40} color="#fff" />

                <div className="ml-3">
                  <div className="flex items-center">
                    <span
                      className={`text-sm font-semibold leading-[20px] ${
                        !item.isConnect ? 'text-text-3' : 'text-text-5'
                      }`}
                    >
                      {item.metadata.name}
                    </span>
                    {item.metadata.isRecommend && appDetail.isCreateFromTemplate && (
                      <div className="ml-[10px] rounded-[4px] bg-@success-color-light px-[10px] text-xs leading-[20px] text-@success-color">
                        推荐
                      </div>
                    )}
                  </div>

                  <div className="mt-1">
                    <div className="flex flex-1 gap-1">
                      {item.metadata.type && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          {modelTitle[item.metadata.type]
                            ? modelTitle[item.metadata.type]
                            : item.metadata.type}
                        </div>
                      )}
                      {item.metadata.reasoning && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          深度思考
                        </div>
                      )}
                      {item.metadata.usedInToolCall && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          工具调用
                        </div>
                      )}
                      {item.metadata.maxContext > 0 && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          {item.metadata.maxContext >= 1000
                            ? `${item.metadata.maxContext / 1000}K`
                            : item.metadata.maxContext}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
                {!item.isConnect && (
                  <div className=" absolute right-0 top-0 z-50 flex items-center rounded-bl-xl rounded-tr-xl bg-@error-color-light px-[10px] py-1">
                    <div className="mr-1 h-1 w-1 rounded-full bg-@error-color" />
                    <div className="text-@error-color">失效</div>
                  </div>
                )}
              </GradientBox>
            ))}
          </div> */}

          <ModalsBoxContent className="flex h-[408px] flex-col gap-2 overflow-y-auto" ref={listRef}>
            {modelList.map((item) => (
              <GradientBox
                key={item.id}
                onClick={() => (!item.isConnect ? undefined : handleSelectValue(item))}
                className={`h-[72px] border-fill-1 bg-fill-1 ${
                  !item.isConnect ? '!cursor-not-allowed' : ''
                } flex items-center py-3 pl-4`}
                active={item.metadata.name === selectValue?.metadata.name}
                hover={item.isConnect}
                bgColor="#F7F8FA"
              >
                <SvgIcon
                  icon={item.metadata.avatar === 'Custom' ? 'CustomModel' : item.metadata.avatar}
                  size={40}
                  color="#fff"
                />

                <div className="ml-3">
                  <div className="flex items-center">
                    <span
                      className={`text-sm font-semibold leading-[20px] ${
                        !item.isConnect ? 'text-text-3' : 'text-text-5'
                      }`}
                    >
                      {item.metadata.name}
                    </span>
                    {item.metadata.isRecommend && appDetail.isCreateFromTemplate && (
                      <div className="ml-[10px] rounded-[4px] bg-@success-color-light px-[10px] text-xs leading-[20px] text-@success-color">
                        推荐
                      </div>
                    )}
                  </div>

                  <div className="mt-1">
                    <div className="flex flex-1 gap-1">
                      {item.metadata.type && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          {modelTitle[item.metadata.type]
                            ? modelTitle[item.metadata.type]
                            : item.metadata.type}
                        </div>
                      )}
                      {item.metadata.reasoning && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          深度思考
                        </div>
                      )}
                      {item.metadata.usedInToolCall && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          工具调用
                        </div>
                      )}
                      {item.metadata.maxContext > 0 && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          {item.metadata.maxContext >= 1000
                            ? `${item.metadata.maxContext / 1000}K`
                            : item.metadata.maxContext}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
                {!item.isConnect && (
                  <div className=" absolute right-0 top-0 z-50 flex items-center rounded-bl-xl rounded-tr-xl bg-@error-color-light px-[10px] py-1">
                    <div className="mr-1 h-1 w-1 rounded-full bg-@error-color" />
                    <div className="text-xs font-medium leading-5 text-@error-color">失效</div>
                  </div>
                )}
              </GradientBox>
            ))}
          </ModalsBoxContent>
        </div>

        <div className="flex-1 border-l-[1px] border-solid border-line-1 pl-6">
          {selectValue ? (
            <Form layout="vertical" form={form} onFinish={handleSubmit}>
              <Form.Item label="温度" name="temperature" style={{ marginBottom: 24 }}>
                {/* <Slider
                  marks={{
                    0: {
                      style: {
                        left: 0,
                        transform: 'none',
                      },
                      label: <div>严谨</div>,
                    },
                    1: {
                      style: {
                        right: 0,
                        transform: 'none',
                        left: 'auto',
                      },
                      label: <div>发散</div>,
                    },
                  }}
                  min={0}
                  max={1}
                  step={0.01}
                  defaultValue={0.3}
                  railStyle={{
                    height: 10, // 可选：调整轨道高度
                    borderRadius: 20,
                  }}
                  trackStyle={{
                    // background: 'linear-gradient(90deg, #ff0000, #00ff00)', // 渐变色背景
                    background: ' linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)',
                    height: 10, // 可选：调整轨道高度
                    borderRadius: 20,
                  }}
                  className="modelSlider"
                /> */}

                <Slider
                  marks={{
                    0: {
                      style: {
                        left: 0,
                        transform: 'none',
                      },
                      label: <div>严谨</div>,
                    },
                    1: {
                      style: {
                        right: 0,
                        transform: 'none',
                        left: 'auto',
                      },
                      label: <div>发散</div>,
                    },
                  }}
                  min={0}
                  max={1}
                  step={0.01}
                  defaultValue={0.3}
                />
              </Form.Item>
              <Form.Item label="最大上下文" name="maxToken" style={{ marginBottom: 24 }}>
                <Slider
                  marks={{
                    0: {
                      style: {
                        left: 0,
                        transform: 'none',
                      },
                      label: <div>0</div>,
                    },
                    [Number(selectValue.metadata.maxResponse)]: {
                      style: { right: 0, transform: 'none', left: 'auto' },
                      label: <div>{selectValue.metadata.maxResponse}</div>,
                    },
                  }}
                  min={0}
                  max={selectValue.metadata.maxResponse}
                  defaultValue={10}
                  // railStyle={{
                  //   height: 10, // 可选：调整轨道高度
                  //   borderRadius: 20,
                  // }}
                  // trackStyle={{
                  //   // background: 'linear-gradient(90deg, #ff0000, #00ff00)', // 渐变色背景
                  //   background: ' linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)',
                  //   height: 10, // 可选：调整轨道高度
                  //   borderRadius: 20,
                  // }}
                  // className="modelSlider"
                />
              </Form.Item>
              <Form.Item label="输出答案" name="isResponseAnswerText" style={{ marginBottom: 24 }}>
                {isWorkflow ? (
                  // <Select
                  //   options={[
                  //     {
                  //       label: '支持',
                  //       value: true,
                  //     },
                  //     {
                  //       label: '不支持',
                  //       value: false,
                  //     },
                  //   ]}
                  //   defaultValue={true}
                  // />
                  <Switch defaultChecked />
                ) : (
                  <div>支持</div>
                )}
              </Form.Item>
              {useReasoning && (
                <Form.Item label="深度思考" name="enableReasoning" style={{ marginBottom: 24 }}>
                  {/* {isWorkflow || !selectValue.metadata.onlyThinkMode ? (
                  
                    <Switch defaultChecked={true} />
                  ) : (
                    <div>支持</div>
                  )} */}

                  {/* <EnableReasoning /> */}

                  {isWorkflow ? (
                    selectValue?.metadata.onlyThinkMode ? (
                      <Tooltip title="仅支持深度思考">
                        <Switch defaultValue disabled={selectValue?.metadata.onlyThinkMode} />
                      </Tooltip>
                    ) : (
                      <Switch />
                    )
                  ) : (
                    <div>{selectValue?.metadata.onlyThinkMode ? '仅支持' : '支持'}</div>
                  )}
                </Form.Item>
              )}
              <Form.Item label="工具调用" style={{ marginBottom: 0 }}>
                <div>{selectValue.metadata.usedInToolCall ? '支持' : '不支持'}</div>
              </Form.Item>
            </Form>
          ) : (
            <NotData />
          )}
        </div>
      </div>
    </Modals>
  );
}

export default DialogModelSelect;
